/* $Id:util.cc jjs $ */
/*
   Copyright (C) 2007 by Jurjen Stellingwerff <jurjen@stwerff.xs4all.nl>
   Part of the Moros Project http://moros.sourceforge.net/

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License.
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY.

   See the COPYING file for more details.
*/
#define DEBUG_ROUTINE "util"

#include <sys/stat.h>
#include <sys/types.h>
#include "util.h"
#include <sstream>
#include <dirent.h>
#include "log.h"

using namespace std;

std::string xml_encode(std::string s) {
    size_t pos=s.find("&");
    while (pos != string::npos) {
        s=s.substr(0,pos) + "&amp;" + s.substr(pos+1);
        pos=s.find("&", pos+1);
    }
    pos=s.find("<");
    while (pos != string::npos) {
        s=s.substr(0,pos) + "&lt;" + s.substr(pos+1);
        pos=s.find("<");
    }
    pos=s.find(">");
    while (pos != string::npos) {
        s=s.substr(0,pos) + "&gt;" + s.substr(pos+1);
        pos=s.find(">");
    }
    return s;
}

string split(string *parm, string txt) {
    size_t pos=(*parm).find(txt);
    string res=(*parm).substr(0,pos);
    if (pos==string::npos) {
        *parm="";
        return res;
    }
    *parm=(*parm).substr(pos+txt.length());
    return res;
}

pos::pos(std::string p) {
    x=0;
    y=0;
    size_t p_pos=p.find(',');
    if (p_pos==string::npos) return;
    x=toint(p.substr(0, p_pos));
    y=toint(p.substr(p_pos+1));
}


string ncpy(int n, string s) {
    string res="";
    for(int t=0; t<n; t++) res+=s;
    return res;
}

int toint(char* s) {
    return atoi(s);
}

int toint(std::string s) {
    return atoi(s.c_str());
}

std::string tostr(long i) {
    std::ostringstream res;
    res << i;
    return res.str();
}

std::string tostr(int i) {
    std::ostringstream res;
    res << i;
    return res.str();
}

long tolong(char* s) {
    return atol(s);
}

long tolong(std::string s) {
    return atol(s.c_str());
}

std::string filename(std::string fname) {
    size_t pos=fname.find("~");
    if (pos < string::npos) {
        fname.replace(pos, 1, getenv("HOME"), 0, strlen(getenv("HOME")));
    }
    return fname;
}

bool isfile(std::string fname) {
    struct stat s;
    stat(fname.c_str(), &s);
    return (S_ISREG(s.st_mode));
}

void directory(std::string dir, sigc::signal<void, std::string> handler) {
    DIR *dr=opendir(dir.c_str());
    if (dr==NULL) return;
    struct dirent *d;
    while (true) {
        d=readdir(dr);
        if (d==NULL) break;
        dbg_calls("Entry: %s type %c", d->d_name, d->d_type);
    }
    closedir(dr);
}
